﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Model;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Properties;

namespace Sunlight.Dispatch.UI {
    public partial class RunningReportFrm : BaseFrm {
        public RunningReportFrm() {
            InitializeComponent();
            this.Load += InterfaceLogFrm_Load;
        }

        private void InterfaceLogFrm_Load(object sender, EventArgs e) {
            var keyValueItems = JsonConvert.DeserializeObject<List<KeyValueItem>>(Settings.Default.DispatchStatus);
            this.cmbDispachStatus.DataSource = keyValueItems;
            this.cmbDispachStatus.DisplayMember = "Value";
            this.cmbDispachStatus.ValueMember = "Key";

            this.pagerControl.OnPageChanged += this.PagerControl_OnPageChanged;
            this.OnControlCreated(this.dgvLogInfo, this.pagerControl);
            this.pagerControl.PageSize = 20;
            this.btnSearch.Click -= this.btnSearch_Click;
            this.btnSearch.Click += this.btnSearch_Click;
            this.txbInfName.KeyDown += TxbCommon_KeyDown;
            this.txbInfName.KeyDown += TxbCommon_KeyDown;
            this.txbKeyWords.KeyDown += TxbCommon_KeyDown;
        }

        private void TxbCommon_KeyDown(object sender, KeyEventArgs e) {
            if(e.KeyCode == Keys.Enter)
                this.SearchGridView(1);
        }

        protected override void LoadInitLocation() {
            base.LoadInitLocation();
            this.dgvLogInfo.Height = this.Height - this.gbCondition.Height - this.pageControlPanel.Height - 60;
            this.dgvLogInfo.Width = this.Width - 50;
            this.dgvLogInfo.ScrollBars = ScrollBars.Vertical;
            this.pageControlPanel.Location = new Point(this.dgvLogInfo.Location.X, this.dgvLogInfo.Location.Y + this.dgvLogInfo.Height);
            this.pageControlPanel.Width = this.dgvLogInfo.Width;
            var locationX = this.dgvLogInfo.Width - this.pagerControl.Width - 50;
            this.pagerControl.Location = new Point(this.pageControlPanel.Location.X + locationX, pagerControl.Location.Y);
        }

        private void PagerControl_OnPageChanged(object sender, PageControlEvemtArgs e) {
            this.SearchGridView(e.PageIndex);
        }

        private void btnSearch_Click(object sender, EventArgs e) {
            SearchGridView(1);
        }

        private void SearchGridView(int pageIndex) {
            if(this.comboBoxDataBase.SelectedItem == null) {
                MessageBoxEx.Show("数据库选项不能为空，请选择");
                return;
            }
            var db = this.comboBoxDataBase.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            this.IsLoading = true;
            using(var dataContext = new MonitorSettingDataContext(db.ConnectString)) {
                IQueryable<TLog> tlog = dataContext.TLog;
                IQueryable<TIntf> tinf = dataContext.TIntf;
                var result = from log in tlog
                             join inf in tinf on log.IntfCode equals inf.Code
                             select new LogViewModel {
                                 Id = log.ID,
                                 SyncNo = log.SyncNo,
                                 SysCode = log.SysCode,
                                 Status = log.Status,
                                 SendTime = log.SendTime,
                                 LogDir = log.LogDir,
                                 ErrMsg = log.ErrMsg,
                                 IntfCode = log.IntfCode,
                                 Url = log.URL,
                                 Code = inf.Code,
                                 Name = inf.Name,
                                 Uper = inf.Uper,
                                 UpFunction = inf.UpFunction,
                                 BlnStep = inf.blnStep == 1 ? "是" : "否",
                                 Downer = inf.Downer,
                                 DownFunction = inf.DownFunction,
                                 MaxNum = inf.MaxNum,
                                 ThreadNum = inf.ThreadNum,
                                 BusinessCode = inf.BusinessCode,
                                 Memo = inf.Memo,
                                 Class = inf.Class,
                                 DataClass = inf.DataClass,
                                 CompleteMethod = inf.CompleteMethod,
                                 Sequential = inf.Sequential,
                                 ConnectString = db.ConnectString
                             };
                var methodName = this.txbMethod.Text;
                var dealerCode = this.txbInfName.Text;
                var keyWords = this.txbKeyWords.Text;
                var dispachStatus = this.cmbDispachStatus.SelectedValue as int?;

                if(!string.IsNullOrEmpty(methodName)) {
                    result = result.Where(d => d.UpFunction.ToLower().Contains(methodName.ToLower()));
                }
                if(!string.IsNullOrEmpty(dealerCode)) {
                    result = result.Where(d => d.SyncNo.ToLower().Contains(dealerCode.ToLower()));
                }
                if(!string.IsNullOrEmpty(keyWords)) {
                    result = result.Where(d => d.UpFunction.ToLower().Contains(keyWords.ToLower())
                                               || d.Code.ToLower().Contains(keyWords.ToLower())
                                               || d.Name.ToLower().Contains(keyWords.ToLower())
                                               || d.Uper.ToLower().Contains(keyWords.ToLower())
                                               || d.DownFunction.ToLower().Contains(keyWords.ToLower())
                                               || d.Downer.ToLower().Contains(keyWords.ToLower())
                                               || d.BusinessCode.ToLower().Contains(keyWords.ToLower())
                                               || d.CompleteMethod.ToLower().Contains(keyWords.ToLower())
                                               || d.Url.ToLower().Contains(keyWords.ToLower()));
                }

                if(dispachStatus != 0) {
                    result = result.Where(d => d.Status == dispachStatus);
                }
                var recordCount = result.Count();
                var data = result.OrderBy(d => d.Id).Skip((pageIndex - 1) * this.pagerControl.PageSize).Take(this.pagerControl.PageSize).ToList();

                this.dgvLogInfo.DataSource = data;
                this.pagerControl.PageIndex = pageIndex;
                this.pagerControl.DrawControl(recordCount);
                this.IsLoading = false;
            }
        }
    }
}
